<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap[mode]" v-model="visible" :width="800" destroy-on-close
        @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120px"
            label-position="right">
            <el-form-item label="名称" prop="name">
				<el-input v-model="form.name" placeholder="请输入名称" clearable maxlength="50" show-word-limit :disabled="form.id != null"></el-input>
			</el-form-item>
            <el-form-item label="价格" prop="price">
                <el-input v-model="form.price" placeholder="请输入课程价格" clearable>
                    <template #append>¥</template>
                </el-input>
            </el-form-item>
            <el-form-item label="购买页图片" prop="buyImages">
                <scUploadMultiple v-model="form.buyImages" title="上传图片" :limit="2"></scUploadMultiple>
            </el-form-item>
			<el-form-item label="介绍" prop="introduction">
				<sc-editor v-model="form.introduction" placeholder="请输入" :height="200"></sc-editor>
			</el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
</template>

<script>
import { defineAsyncComponent } from 'vue'
const scEditor = defineAsyncComponent(() => import('@/components/scEditor'))
export default {
    emits: ['success', 'closed'],
	components: {
		scEditor
	},
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增',
                edit: '编辑',
                show: '查看'
            },
            visible: false,
            isSaveing: false,
            //表单数据
            form: this.getDefaultRuleForm(),
            //验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                price: [
                    { required: true, message: '请输入正确的课程价格', trigger: 'blur' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '只能为数字且最多只能为2位小数', trigger: 'blur'},
                ],
                buyImages: [
                    { required: true, message: '请上传图片', trigger: 'blur' },
                ],
                sort: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            var myreg = /^(-|[0-9])\d*$/;
                            if (!value) {
                                callback(new Error('请输入排序'))
                            } else if (!myreg.exec(value)) {
                                callback(new Error('只能输入整数'))
                            } else {
                                callback()
                            }
                        }
                    },
                ],
            },
        }
    },
    mounted() {
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                }

                let data = {}
                for (let key in this.form) {
                    data[key] = this.form[key]
                }

                //购买页图片处理
				let _buyImages = []
				if (data.buyImages && typeof(data.buyImages) === 'string') {
					data.buyImages.split(",").forEach(item => {
						item && _buyImages.push(item.match(/.+\.com(.+)/)[1])
					})
				} else if(data.buyImages && data.buyImages.length > 0) {
					data.buyImages.forEach((item) => {
						_buyImages.push(item.path)
					})
				}

				data.param.buyImages = _buyImages
                delete data.buyImages

                try {
                    this.isSaveing = true;
                    if (this.form.id) {
                        await this.$API.product.action.put(data)
                    } else {
                        await this.$API.product.action.post(data)
                    }
                    this.$emit('success', this.form, this.mode)
                    this.visible = false;
                    this.$notify.success("保存成功")
                } finally {
                    this.isSaveing = false;
                }
            })
        },
        //表单注入数据
        async setData(row) {
            this.loading = true
			await this.$API.product.action.get({id: row.id}).then(res => {
                this.loading = false
                let _data = res.data
                let _form = {}
                for(let key in _data) {
                    if (key == 'status' || key == 'type') {
                        _form[key] = _data[key] ? _data[key].value : 1
                        continue
                    }

                    if (key == 'icon') {
                        _form[key] = _data[key] ? _data[key].url : ''
                        continue
                    }

                    if (key == 'param') {
                        _form[key] = _data[key] ? _data[key] : {}
                        continue
                    }

                    _form[key] = _data[key]
                }

                const buyImages = _data.param ? _data.param.buyImages : []
                if (buyImages && buyImages.length > 0) {
                    let images = []
                    buyImages.forEach(item => {
                        item.url && images.push(item.url)
                    })
                    _form.buyImages = images.join(",")
                }
                
                this.form = _form
                console.log('form', this.form)
            }).finally(() => {
				this.loading = false
			})
        },
        getDefaultRuleForm() {
            return {
                id: null,
                type: 1,
                name: '',
                icon: '',
				introduction: '',
				sort: '',
				price: 0,
				status: 1,
                param: {},
                buyImages: []
            }
        },
    }
}
</script>

<style>
</style>
